package com.d3works.apps.purchase.service.app;

import com.d3works.apps.base.db.AppPurchase;
import com.d3works.apps.base.db.Company;
import com.d3works.apps.base.db.repo.AppPurchaseRepository;
import com.d3works.apps.base.db.repo.CompanyRepository;
import com.d3works.apps.base.service.app.AppBaseServiceImpl;
import com.d3works.apps.purchase.db.PurchaseConfig;
import com.d3works.apps.purchase.db.repo.PurchaseConfigRepository;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;
import java.util.List;

@Singleton
public class AppPurchaseServiceImpl extends AppBaseServiceImpl implements AppPurchaseService {

  @Inject private AppPurchaseRepository appPurchaseRepo;

  @Inject private CompanyRepository companyRepo;

  @Inject private PurchaseConfigRepository purchaseConfigRepo;

  @Override
  public AppPurchase getAppPurchase() {
    return appPurchaseRepo.all().fetchOne();
  }

  @Override
  @Transactional
  public void generatePurchaseConfigurations() {

    List<Company> companies = companyRepo.all().filter("self.purchaseConfig is null").fetch();

    for (Company company : companies) {
      PurchaseConfig purchaseConfig = new PurchaseConfig();
      purchaseConfig.setCompany(company);
      purchaseConfigRepo.save(purchaseConfig);
    }
  }
}
